import React, { useState, useRef, useEffect, useCallback } from "react";
import { useHistory } from "react-router-dom";

import { Button, Input, AutoComplete, Tabs } from "antd";
import {
  BellOutlined,
  MessageOutlined,
  UserOutlined,
  UnorderedListOutlined,
  UserSwitchOutlined,
  HeartOutlined,
  SettingOutlined,
  EditOutlined,
  UserAddOutlined,
  PoweroffOutlined,
  DeleteOutlined,
} from "@ant-design/icons";

import { apiGetSearch, apiGetHotSearch } from "@/api/index";

import "./header.less";

const { TabPane } = Tabs;

let options: any = [
  {
    label: <span style={{ fontSize: 14 }}>热搜</span>,
    options: [],
  },
  {
    label: (
      <div className="search-title">
        <span>搜索历史</span>
        <span style={{ cursor: "pointer" }}>
          <DeleteOutlined style={{ marginRight: 4 }} />
          清空
        </span>
      </div>
    ),
    options: [],
  },
];

const Header: React.FC = () => {
  const history = useHistory(); // 路由历史信息
  const render = useState(0)[1]; // 用来触发页面跟新
  interface get {
    [key: string]: any;
  }
  const page: get = useRef({
    searchFocus: false, // 搜索框是否聚焦
    showNotice: false, // 显示通知
    showMessage: false, // 显示私信
    showMe: false, // 显示个人设置
    hotSearch: [], // 热门搜索
    isHot: false, // 当前是否显示热门搜索
    navTitle: "首页",
  });
  // 定义函数
  const s = () => Math.random();

  // 搜索框聚焦
  const searchFocus = () => {
    page.current.searchFocus = true;
    render(s);
  };
  // 搜索框失去焦点
  const searchBlur = () => {
    page.current.searchFocus = false;
    render(s);
  };
  // 点击空白取消弹框方法
  const closePop = useCallback(
    (e: any) => {
      const notice = document.querySelector(".header-page .notice-icon-box");
      const message = document.querySelector(".header-page .message-box");
      const me = document.querySelector(".header-page .img-box-wrap");
      if (notice) {
        if (!notice.contains(e.target)) {
          page.current.showNotice = false;
          render(s);
        }
      }
      if (message) {
        if (!message.contains(e.target)) {
          page.current.showMessage = false;
          render(s);
        }
      }
      if (me) {
        if (!me.contains(e.target)) {
          page.current.showMe = false;
          render(s);
        }
      }
    },
    [render]
  );
  // 切换私信和通知的弹框
  const toggleMessage = (str: string): void => {
    page.current[str] = !page.current[str];
    render(s);
  };
  // 设置搜索结果显示
  const fillSearchData = (searchRes: Array<object>) => {
    let searchHistory = [{ value: "搜索历史" }];
    const list = [
      {
        label: <span style={{ fontSize: 14 }}>热搜</span>,
        options: searchRes.map((i: any, index: number) => {
          return {
            value: i.query,
            label: (
              <div>
                <span>{i.query}</span>
                <span
                  className={`iconfont iconremen ${
                    page.current.isHot && index < 3 ? "hot-icon" : "none"
                  }`}
                ></span>
              </div>
            ),
          };
        }),
      },
      {
        label: (
          <div className="search-title">
            <span>搜索历史</span>
            <span style={{ cursor: "pointer" }}>
              <DeleteOutlined style={{ marginRight: 4 }} />
              清空
            </span>
          </div>
        ),
        options: searchHistory,
      },
    ];
    return list;
  };
  // 搜索框输入触发
  const onSearch = async (value: string) => {
    if (!value) {
      page.current.isHot = true;
      options = fillSearchData(page.current.hotSearch);
      render(s);
      return;
    }
    page.current.isHot = false;
    let res: any = await apiGetSearch({ q: value });
    options = fillSearchData(res.suggest);
    page.current.isHot = false;
    render(s);

    // const list = res.suggest;
  };
  // 导航栏切换
  const toggleNav = (title: string) => {
    page.current.navTitle = title;
    if (title === "首页") {
      history.push("/");
    }
    if (title === "发现") {
      history.push("/find");
    }
    render(s);
  };

  useEffect(() => {
    document.addEventListener("mouseup", closePop);
    apiGetHotSearch().then((res: any) => {
      page.current.isHot = true;
      page.current.hotSearch = res.top_search.words; // 储存热门搜索
      options = fillSearchData(res.top_search.words); // 渲染搜索结果
    });

    return () => {
      document.removeEventListener("mouseup", closePop);
    };
  }, [closePop]);

  return (
    <nav className="header-page">
      <span className="header">
        <div className="left">
          <div className="title">知乎</div>
          <span
            className={`item ${
              page.current.navTitle === "首页" ? "active" : ""
            }`}
            onClick={() => toggleNav("首页")}
          >
            首页
          </span>
          <span
            className={`item ${
              page.current.navTitle === "发现" ? "active" : ""
            }`}
            onClick={() => toggleNav("发现")}
          >
            发现
          </span>
          <span
            className={`item ${
              page.current.navTitle === "等你来答" ? "active" : ""
            }`}
            onClick={() => toggleNav("等你来答")}
          >
            等你来答
          </span>
          <AutoComplete
            className={`item auto-complete ${
              page.current.searchFocus ? "auto-complete-focus" : ""
            } `}
            dropdownClassName={`certain-category-search-dropdown ${
              page.current.isHot ? "" : "no-hot"
            }`}
            dropdownMatchSelectWidth={500}
            options={options}
            onChange={onSearch}
          >
            <Input.Search
              className={`item auto-complete ${
                page.current.searchFocus ? "auto-complete-focus" : ""
              }`}
              size="large"
              placeholder="输入内容搜索"
              onFocus={searchFocus}
              onBlur={searchBlur}
            />
          </AutoComplete>
          <div
            className={`item questions ${
              page.current.searchFocus ? "questions-hide" : ""
            }`}
          >
            <Button type="primary">提问</Button>
          </div>
        </div>

        <div className="right">
          {/* 通知部分 */}
          <div className=" item notice-box">
            <div className="notice-icon-box">
              <BellOutlined
                className="icon  notice-icon "
                onClick={() => toggleMessage("showNotice")}
              />
              <div
                className={`none opacity0  ${
                  page.current.showNotice ? "notice" : ""
                }`}
              >
                <Tabs defaultActiveKey="1">
                  <TabPane
                    tab={<UnorderedListOutlined className="icon" />}
                    key="1"
                    className="tab-no-content"
                  >
                    <span className="iconfont iconlingdang icon"></span>
                    <span className="text-gray">暂无消息</span>
                  </TabPane>
                  <TabPane
                    tab={<UserSwitchOutlined className="icon" />}
                    key="2"
                    className="tab-no-content"
                  >
                    <span className="iconfont iconlingdang icon"></span>
                    <span className="text-gray">暂无消息</span>
                  </TabPane>
                  <TabPane
                    tab={<HeartOutlined className="icon" />}
                    key="3"
                    className="tab-no-content"
                  >
                    <span className="iconfont iconlingdang icon"></span>
                    <span className="text-gray">暂无消息</span>
                  </TabPane>
                </Tabs>

                <div className="footer">
                  <span className="item">
                    <SettingOutlined style={{ marginRight: 2 }} />
                    设置
                  </span>
                  <span className="item">查看全部通知</span>
                </div>
              </div>
            </div>
          </div>

          {/* 私信部分 */}
          <div className="item message-box">
            <MessageOutlined
              className="icon "
              onClick={() => toggleMessage("showMessage")}
            />
            <div
              className={`none opacity0 ${
                page.current.showMessage ? "message" : ""
              }`}
            >
              <div className="title-text">我的私信</div>
              <div className="footer">
                <span className="item">
                  <EditOutlined style={{ marginRight: 2 }} />
                  设置
                </span>
                <span className="item">查看全部通知</span>
              </div>
            </div>
          </div>
          {/* 头像部分 */}
          <div className="img-box-wrap item">
            <div className="img-box" onClick={() => toggleMessage("showMe")}>
              <img className="img" src="" alt="" />
            </div>
            <ul
              className={`none opacity0 me-box-wrap ${
                page.current.showMe ? "me-box" : ""
              }`}
            >
              <li className="li">
                <UserOutlined
                  className="text-black"
                  style={{ marginRight: 6 }}
                />
                我的主页
              </li>
              <li className="li">
                <UserAddOutlined
                  className="text-black"
                  style={{ marginRight: 6 }}
                />
                创作中心
              </li>
              <li className="li">
                {" "}
                <SettingOutlined
                  className="text-black"
                  style={{ marginRight: 6 }}
                />
                设置
              </li>
              <li className="li">
                <PoweroffOutlined
                  className="text-black"
                  style={{ marginRight: 6 }}
                />
                退出
              </li>
            </ul>
          </div>
        </div>
      </span>
    </nav>
  );
};

export default Header;
